import { defineComponent, onMounted, reactive, ref, Teleport } from "vue";
import styles from "./GroupDetail.module.less";
import Breadcrumb from "@/components/public/Breadcrumb/Breadcrumb";
import { useRoute, useRouter } from "vue-router";
import { CheckCircleFilled, HeartOutlined, HeartFilled, LoadingOutlined } from "@ant-design/icons-vue";
import importantReminder from "./importantReminder";
import { imgPath } from "@/common/utils";
import { useStore as useUserStore } from "@/store/user";
import { message } from "ant-design-vue";
import dayjs from 'dayjs';
import { $getProductDetail, $getProductListDetail } from "@/api/product/product";
import { text } from "stream/consumers";
import { $userAuthStatus } from "@/api/account/account";
import { useStore as useCountryStore } from "@/store/countrys";

export default defineComponent({
  name: 'GroupDetail',
  setup() {
    const router = useRouter();
    const route = useRoute();
    const useStore = useUserStore();
    const countryStore = useCountryStore();

    const state = reactive({
      id: route.query.id,
      name: '',
      insureImg: 'https://www.chinatourins.com/_gw/res-svc/res/v3/download?fileId=1758453447454391371&free=1',
      tags: [],
      salesArea: '',
      ageNote: '',
      during: '',
      maxCount: 1,
      saleNum: '2024',
      rate: '',
      start_date: '',
      end_date: '',
      travel_route: '',
      travel_no: '',
      premium: '1.10',
      max_days: '4',
      min_days: '2',
      is_collect: false,
      diffInMs: '',
      is_days: true,
      status: 0, //用户认证状态
      disabled: true,
      countryCode: null, //国家
      isCountry: false,
    } as any)

    // 面包屑
    const breadcrumbState = ref([
      () => <span class={styles['Breadcrumb-Home']} onClick={() => { router.push('/home') }}>首页</span>,
      () => <span class={styles['Breadcrumb-GroupList']} onClick={() => { router.push('/GroupList') }}>旅游意外险</span>,
      () => <span class={styles['Breadcrumb-GroupDetail']}>{state.name}</span>,
    ])

    // 内容头
    const GroupHeader = () => (
      <div class={styles['group-header']}>
        <div class={styles['productName']}>{state.name}</div>
        <div class={styles['insureImg']}>
          {/* <img src={state.insureImg} /> */}
        </div>
      </div>
    )

    // 产品基础信息
    const ProductBasic = () => (
      <div class={styles['product-basic']}>
        <div class={styles.left}>
          <div class={styles.liabilityTag}>
            {
              state.tags.map((item: any) => (
                <div class={styles['liabilityTag-item']}>
                  <CheckCircleFilled class={styles.icon} />
                  <span>{item}</span>
                </div>
              ))
            }
          </div>
          <div class={styles.basic_info}>
            <div class={styles['basic_info-item']}>
              销售区域：
              <span>{state.salesArea}</span>
            </div>
            <div class={styles['basic_info-item']}>
              承保年龄：
              <span>{state.ageNote}</span>
            </div>
            <div class={styles['basic_info-item']}>
              保险期间：
              <span>{state.during}</span>
            </div>
            <div class={styles['basic_info-item']}>
              最大购买份数
              <span>{state.maxCount}份</span>
            </div>
          </div>
        </div>
        {/* <div class={styles.right}>
          <div class={styles['right-item']}>
            <div class={styles['item-label']}>累计销量</div>
            <div class={styles['item-value']}>{state.saleNum}</div>
          </div>
        </div> */}
      </div>
    )

    //获取产品详情
    const getProductDetail = () => {
      $getProductListDetail({ product_id: state.id }).then((res: any) => {
        state.name = res?.data?.product?.name || '';
        state.tags = res?.data?.product?.liability_tag || [];
        state.salesArea = res?.data?.product?.sales_area || '';
        state.ageNote = res?.data?.product?.insure_age || '';
        state.during = res?.data?.product?.insure_day || '';
        state.maxCount = res?.data?.product?.sales_num || '';
        state.premium = res?.data?.product?.product_price || '';
        state.max_days = res?.data?.product?.plan?.max_days || '';
        state.min_days = res?.data?.product?.plan?.min_days || '';
        noticeTitleState.value = res?.data?.product?.insurance?.client_notice?.title || "";
        noticeState.value = res?.data?.product?.insurance?.client_notice?.content || "";
        guideState.value = res?.data?.product?.insurance?.term?.notice || "";
        termsState.value = res?.data?.product?.insurance?.term_rel || [];
        protectItems.value = res?.data?.product?.protectItems || [];
        priceList.value = res?.data?.product?.priceList || [];
        planList.value = res?.data?.productList || [];
        actived.value = Number(res?.data?.product?.id || '');
        if ((res?.data?.product?.plan_code).includes('LEAJ')) {
          state.isCountry = true;
          console.log('是境外游')
        } else {
          state.isCountry = false;
          console.log('是境内游')
        }
      })
    }

    onMounted(() => {
      getProductDetail()
    })
    // 跳转投保
    const doInsure = () => {
      if (!useStore.token) {
        message.error('请先登录');
        return;
      }
      if (!state.start_date || !state.end_date) {
        message.error('保险期间未选，请选择时间');
        return;
      }
      if (!state.travel_route) {
        message.error('请填写旅游线路');
        return;
      }
      // if (state.isCountry && !state.countryCode) {
      //   message.error('请选择国家')
      // }
      console.log(actived.value),
        router.push({
          path: '/AccidentInsurePage',
          query: {
            product: actived.value,
            start_date: state.start_date,
            end_date: state.end_date,
            travel_route: state.travel_route,
            travel_no: state.travel_no,
            countryCode:state.countryCode,
          }
        })
      const dom: any = document.getElementById("app");
      dom.scrollTop = 0;
    }

    const disabledDate = (current: any) => {
      return current && current <= dayjs().endOf('day');
    };

    const disabledDateEnd = (current: any) => {
      return current && current < dayjs(state.start_date).startOf('day');
    }

    const dateStateChange = () => {
      state.end_date = ''
    }

    const dateEndChange = () => {
      state.diffInMs = Math.ceil(Math.abs(new Date(state.end_date).getTime() - new Date(state.start_date).getTime()) / (24 * 60 * 60 * 1000)) + 1;
      state.is_days = false;
    }
    //计划
    const planList = ref([]);

    const actived = ref(0);


    //选择计划
    const clickPlan = (item: any) => {
      if (!item.plan_code) {
        return
      }
      if (item.id === actived.value) {
        return
      }
      actived.value = item.id;
      if ((item.plan_code).includes('LEAJ')) {
        state.isCountry = true;
        console.log('是境外游')
      } else {
        state.isCountry = false;
        console.log('是境内游')
      }
      loading.value = false;
      $getProductDetail({ product_id: item.id }).then((res: any) => {
        state.name = res?.data?.product?.name || '';
        state.tags = res?.data?.product?.liability_tag || [];
        state.salesArea = res?.data?.product?.sales_area || '';
        state.ageNote = res?.data?.product?.insure_age || '';
        state.during = res?.data?.product?.insure_day || '';
        state.maxCount = res?.data?.product?.sales_num || '';
        state.premium = res?.data?.product?.product_price || '';
        state.max_days = res?.data?.product?.plan?.max_days || '';
        state.min_days = res?.data?.product?.plan?.min_days || '';
        noticeTitleState.value = res?.data?.product?.insurance?.client_notice?.title || "";
        noticeState.value = res?.data?.product?.insurance?.client_notice?.content || "";
        guideState.value = res?.data?.product?.insurance?.term?.notice || "";
        termsState.value = res?.data?.product?.insurance?.term_rel || [];
        protectItems.value = res?.data?.product?.protectItems || [];
        priceList.value = res?.data?.product?.priceList || [];
        planList.value = res?.data?.productList || [];
        console.log(protectItems.value);
        loading.value = true;
        message.success('已选择新计划');
      }).catch(() => {
        loading.value = true;
      })
    }
    //国家搜索
    const filterOption = (input: string, option: any) => {
      return option.label.indexOf(input) >= 0
    };
    // 产品选择信息
    const ProductSelect = () => (
      <div class={styles['product-select']}>
        <div class={styles.left}>
          <div class={styles['sign-rows']}>
            <div class={styles['sign-row']}>
              <div class={styles['sign-col']}>
                <div class={styles['col-label']}>选择计划：</div>
                <div class={styles['col-value']}>
                  <div class={styles.plans}>
                    {
                      planList.value.map((item: any) => (
                        <div class={[styles['plan-item'], item.id === actived.value && styles.actived,
                        item.plan_code === '' && styles.noActived, item.id === actived.value && styles.select]}
                          onClick={() => { clickPlan(item) }}
                        >{item.plan_name}</div>
                      ))
                    }
                  </div>
                </div>
              </div>
            </div>
            <div class={styles['sign-row']}>
              <div class={styles['sign-col']}>
                <div class={styles['col-label']}>保险期间：</div>
                <div class={styles['col-value']}>
                  <a-date-picker class={styles['date-picker']} v-model:value={state.start_date} placeholder="起保时间" valueFormat="YYYY-MM-DD" disabled-date={disabledDate} onChange={() => { dateStateChange() }} />
                  <span class={styles['date-picker-connect']}>至</span>
                  <a-date-picker class={styles['date-picker']} v-model:value={state.end_date} placeholder="终止时间" disabled={!state.start_date}
                    valueFormat="YYYY-MM-DD" disabled-date={disabledDateEnd} onChange={() => { dateEndChange() }} />
                  {state.is_days || <div style={{ marginLeft: '10px' }}>共{state.end_date ? state.diffInMs : 0}天</div>}
                </div>
              </div>
            </div>
            <div class={styles['sign-row']}>
              <div class={styles['sign-col']}>
                <div class={styles['col-label']}>旅游线路：</div>
                <div class={styles['col-value']}>
                  <a-input class={styles['travel-route']} v-model:value={state.travel_route} placeholder="请填写简写线路（目的地），100字符以内" />
                </div>
              </div>
              <div class={styles['sign-col']}>
                <div class={styles['col-label']}>旅游编号：</div>
                <div class={styles['col-value']}>
                  <a-input class={styles['travel-no']} v-model:value={state.travel_no} placeholder="请填写旅游编号" />
                </div>
              </div>
            </div>
            {/* <div class={styles['sign-row']} v-show={state.isCountry}>
              <div class={styles['sign-col']}>
                <div class={styles['col-label']}>目的地国家：</div>
                <div class={styles['col-value']}>
                  <a-select
                    show-search
                    v-model={[state.countryCode, "value"]}
                    options={countryStore.countrys}
                    style={{ width: '210px' }}
                    filterOption={(input: string, option: any) => filterOption(input, option)}
                    placeholder="请选择国家"
                  >
                  </a-select>
                </div>
                <div class={styles.tips}>（当为境外游时,需选择目的地国家）</div>
              </div>
            </div> */}
            <div class={styles['sign-row']}>
              <div class={styles['sign-col']}>
                <div class={styles['col-label']}>保费：</div>
                <div class={styles['col-value']}>
                  <div class={styles['premium']}>
                    ￥<span>{state.premium}</span>起
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class={styles['submit-box']}>
            <div class={styles['submit-btn']} onClick={() => { doInsure() }}>立即投保</div>
          </div>
        </div>
        {/* <div class={styles.right}>
          <div class={styles['collect-box']} onClick={() => { state.is_collect = !state.is_collect }}>
            <HeartOutlined class={styles['collect-icon']} v-show={!state.is_collect} />
            <HeartFilled class={[styles['collect-icon'], state.is_collect && styles['is-collect']]} v-show={state.is_collect} />
            <span>收藏产品</span>
          </div>
        </div> */}
      </div>
    )

    // 底部
    const SalesRange = () => (
      <div class={styles['sales-range']}>
        <div class={styles.col}>
          <span class={styles['col-label']}>在线服务：</span>
          <span class={styles['col-value']}>投保 | 核保 | 批改 | 退保 | 报案 | 理赔 | 投诉</span>
        </div>
        <div class={styles.col}>
          <span class={styles['col-label']}>线下服务：</span>
          <span class={styles['col-value']}>
            请致电 <span class={styles.tel}>400-855-8990</span>
          </span>
        </div>
      </div>
    )

    // 内容
    const GroupContent = () => (
      <div class={styles['group-content']}>
        <GroupHeader />
        <ProductBasic />
        <ProductSelect />
        <SalesRange />
      </div>
    )

    // 标题
    const SchemeTitle = (props: any) => (
      <div class={styles['scheme-title']}>
        <span>{props.title}</span>
      </div>
    )

    const noticeTitleState = ref("客户告知书")
    const noticeState = ref("")

    // 客户告知书
    const Notice = () => (
      <div class={styles.notice}>
        <SchemeTitle title={noticeTitleState.value} />
        <div class={styles.content}>
          <div v-html={noticeState.value}></div>
        </div>
      </div>
    )
    const protectItems = ref([]);
    const priceList = ref([]);
    // 保险方案
    const Plan = () => (
      <div class={styles.plan}>
        {/* <SchemeTitle title="特别提示" />
        <div class={styles.insureSchemeText} v-html={insureSchemeText}></div> */}
        <SchemeTitle title="保险责任(详见条款)" />
        <div class={styles['plan-table']}>
          <div class={styles['table-rows']}>
            {
              protectItems.value.map((itemX: any) => (
                <div class={styles['table-row']}>
                  {
                    itemX.map((itemY: any) => (
                      <div class={styles['table-col']}>
                        <div class={styles['cell']}>{itemY}</div>
                      </div>
                    ))
                  }
                </div>
              ))
            }
          </div>
        </div>
        {
          useStore.token == '' ? <div class={styles['login-type']}>登录后查看</div> : <>
            <SchemeTitle title="保费" />
            <div class={styles.tableBar}>
              {
                priceList.value.map((itemP: any) => (
                  <div class={styles['table-row']}>
                    {
                      itemP.map((itemL: any) => (
                        <div class={styles['table-col']}>
                          <div class={styles['content-item']}>{itemL}</div>
                        </div>
                      ))
                    }
                  </div>
                ))
              }
            </div>
          </>
        }
      </div>
    )

    const guideState = ref("")

    // 投保须知
    const Guide = () => (
      <div class={styles.guide}>
        <SchemeTitle title="投保须知" />
        <div class={styles['guide-content']}>
          <div v-html={guideState.value}></div>
        </div>
      </div>
    )

    // 重要提醒
    const ImportantReminder = () => (
      <div class={styles['important-reminder']}>
        <SchemeTitle title="重要提醒" />
        <div class={styles['important-reminder-content']} v-html={importantReminder}></div>
      </div>
    )

    const termsState = ref([])

    // 保险条款
    const Terms = () => (
      <div class={styles['terms']}>
        <SchemeTitle title="保险条款" />
        <div class={styles['terms-container']}>
          {/* <div class={styles['terms-title']}>
            景区意外险（互联网专属）方案一
          </div> */}
          <div class={styles['terms-table-header']}>
            <div class={styles['header-col']}>
              <span>保险条款</span>
            </div>
            <div class={styles['header-operate']}>
              <span>操作</span>
            </div>
          </div>
          <div class={styles['terms-table-rows']}>
            {
              termsState.value.map((item: any) => (
                <div class={styles['terms-table-row']}>
                  <div class={styles['row-col']}>
                    <span>{item.name}</span>
                  </div>
                  <div class={styles['row-operate']}>
                    <div class={styles.btns}>
                      <span onClick={() => { window.open(item.file) }}>查看</span>
                    </div>
                  </div>
                </div>
              ))
            }
          </div>
        </div>
      </div>
    )

    const questionsState = ref([
      {
        q: '什么是合理医疗费用？',
        a: '合理医疗费用指符合投保所在地的基本医疗保险规定的药品目录、诊疗项目目录、服务设施范围和支付标准的医疗费用，不包括基本医疗保险规定的由个人先行自付部分的医疗费用以及基本医疗保险规定之外的应当由个人全额负担的自费费用。',
      },
      {
        q: '如何获得电子保单？',
        a: '投保成功后，您可以通过“会员中心→订单列表”很方便的查询及下载您的电子保单，电子保单具有和纸质保单相同的法律效力。',
      },
    ])

    // 常见问题
    const Questions = () => (
      <div class={styles.questions}>
        <SchemeTitle title="常见问题" />
        <div class={styles['questions-rows']}>
          {
            questionsState.value.map((item: any) => (
              <div class={styles['questions-row']}>
                <div class={styles['row-question']}>
                  <img src={imgPath("/Question.png")} />
                  <span>{item.q}</span>
                </div>
                <div class={styles['row-answer']}>
                  <img src={imgPath("/Answer.png")} />
                  <span>{item.a}</span>
                </div>
              </div>
            ))
          }
        </div>
      </div>
    )


    // 资料列表
    const insureListState = reactive({
      list: [
        {
          label: '客户告知书',
          value: '客户告知书',
          el: () => <Notice />
        },
        {
          label: '保险方案',
          value: '保险方案',
          el: () => <Plan />
        },
        {
          label: '投保须知',
          value: '投保须知',
          el: () => <Guide />
        },
        {
          label: '保险条款',
          value: '保险条款',
          el: () => <Terms />
        },
        {
          label: '常见问题',
          value: '常见问题',
          el: () => <Questions />

        },
      ],
      checked: '保险方案',
    })

    // 客户告知书等
    const InsureList = () => (
      <div class={styles['insure-list']}>
        <div class={styles['tablist']}>
          {
            insureListState.list.map((item: any) => (
              <div class={[styles['tab-item'], item.value === insureListState.checked && styles.isChecked]} onClick={() => insureListState.checked = item.value}>
                <span>{item.label}</span>
              </div>
            ))
          }
        </div>
        <div class={styles['tab-pane']}>
          {
            insureListState.list?.find?.((x: any) => x.value === insureListState.checked)?.el?.()
          }
        </div>
      </div>
    )

    const loading = ref(true);

    return () => (
      <div class={styles['group-detail']}>
        <div class={styles['group-detail-container']}>
          <Breadcrumb list={breadcrumbState.value} />
          <GroupContent />
          <InsureList />
        </div>
        {
          loading.value ||
          (
            <Teleport to="body">
              <div class={styles['statement-floating']}>
                <div class={styles['loading-box']}>
                  <div class={styles.content}>
                    <LoadingOutlined class={styles.icon} />
                  </div>
                </div>
              </div>
            </Teleport>
          )
        }
      </div>
    )
  }
})